# -*- coding: utf-8 -*-
# !/usr/bin/env python

__author__ = 'zhengtx'

import sys

from flask import Flask, jsonify, request

sys.path.append('../')

from proxy.Manager.ProxyManager import ProxyManager

app = Flask(__name__)


api_list = {
    'get': 'get an usable http proxy',
    # 'get_https': 'get an usable http sproxy',
    'refresh': 'refresh proxy pool',
    'getAll': 'get all proxy from proxy pool',
    # 'get_all_https': 'get all https proxy from proxy pool',
    'delete?proxy=127.0.0.1:8080': 'delete an unable proxy',
    # 'delete_https?proxy=127.0.0.1:8080': 'delete an unable https proxy',
}


@app.route('/')
def index():
    return jsonify(api_list)


@app.route('/get/')
def gethttp():
    proxy = ProxyManager().get()
    return proxy if proxy else None


@app.route('/get_https/')
def gethttps():
    proxy = ProxyManager().gethttps()
    return proxy if proxy else None


@app.route('/refresh/')
def refresh():
    # TODO refresh会有守护程序定时执行，由api直接调用性能较差，暂不使用
    ProxyManager().refresh()
    pass
    return 'success'


@app.route('/getAll/')
def getAllhttp():
    proxies = ProxyManager().getAll()
    if proxies is None:
        return ""
    return jsonify(list(proxies))


@app.route('/get_all_https/')
def getAllhttps():
    proxies = ProxyManager().getAllhttps()
    if proxies is None:
        return ""
    return jsonify(list(proxies))


@app.route('/delete/', methods=['GET'])
def deletehttp():
    proxy = request.args.get('proxy')
    ProxyManager().delete(proxy)
    return 'success'


@app.route('/delete_https/', methods=['GET'])
def deletehttps():
    proxy = request.args.get('proxy')
    ProxyManager().deletehttps(proxy)
    return 'success'


@app.route('/get_status/')
def get_status():
    status = ProxyManager().get_status()
    return jsonify(status)


def run():
    app.run(host='127.0.0.1', port=5000)

if __name__ == '__main__':
    run()
